﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MaxLeaf.Common;
using MaxLeaf.DB;
using System.Data;
using MySql.Data.MySqlClient;
using System.Data.SqlClient;

namespace MaxLeaf.DAL.W2K
{
   


    public class goods_categoryDAL : BaseDAL
    {
        public goods_categoryDAL()
            : base()
        {
            strK3TableName = "t_ComCategory";
            strWebTableName = "goods_category";

            strK3MapKeyFieldName = "FitemID";
            strWebMapKeyFieldName = "cat_id";
            strWebMapKeyTableName = "k3_goods_category";

            //strK3DestRealKeyFieldName = "FName";
            //strWebOrgDestRealKeyFieldName = "cat_name";


            strFieldNames = "FNumber,FName,FTaxRate,FOrderFlag,FIsAllowLong,FCanModifyPrice,FPointsRate";

            strFItemClassID = Const.FItemClassID_Category;
        }

        public override void Delete(DBAccess dbOrgWebReadCon, DBAccess dbOrgWebWriteCon, DBAccess dbDestK3Con, string strKeyValue)
        {

            string strDestKeyValue = GetDestKeyValue(dbOrgWebReadCon, dbOrgWebWriteCon, dbDestK3Con, strKeyValue);
            if (strDestKeyValue.Length == 0)
            {
                return;
            }

            Dictionary<string, object> dictCond = new Dictionary<string, object>() { { strK3MapKeyFieldName, strDestKeyValue } };            
            KeyValuePair<string, IDataParameter[]> kvp = dbDestK3Con.CreateCondParam(dictCond);
            string strSql = string.Format(@"delete from {0} where  {1}", strK3TableName, kvp.Key);
            dbDestK3Con.ExecuteSql(strSql, kvp.Value);

            dictCond = new Dictionary<string, object>() { { "FitemID", strDestKeyValue } };
            kvp = dbDestK3Con.CreateCondParam(dictCond);
            strSql = string.Format(@"delete from {0} where  {1}", "t_item", kvp.Key);
            dbDestK3Con.ExecuteSql(strSql, kvp.Value);

            dictCond = new Dictionary<string, object>() { { "tablename", strWebMapKeyTableName }, { "K3KeyValue", strDestKeyValue } };
            kvp = dbDestK3Con.CreateCondParam(dictCond);
            strSql = string.Format(@"delete from {0} where  {1}", "mWebK3KeyMap", kvp.Key);
            dbDestK3Con.ExecuteSql(strSql, kvp.Value);

             strSql = @"insert into mLog(logtype,keyvalue,logstatus)
                values(@logtype,@keyvalue,@logstatus)";
            dbDestK3Con.ExecuteSql(strSql, dbDestK3Con.CreateCondParam(new Dictionary<string, object>() { 
                 {"logtype",LogType.goods_category.ToString()}
                 ,{"keyvalue",strDestKeyValue}
                 ,{"logstatus","2"}
             }).Value);

        }

        public override int Update(DBAccess dbOrgWebReadCon, DBAccess dbOrgWebWriteCon, DBAccess dbDestK3Con, string strKeyValue)
        {
            KeyValuePair<string,IDataParameter[]> kvp=dbOrgWebReadCon.CreateCondParam(new Dictionary<string,object>(){{"cat_id",strKeyValue}});
            DataRow drOrg = dbOrgWebReadCon.GetDataFirstRow(string.Format("select 0+cat_level as cat_level from goods_category where {0}", kvp.Key), kvp.Value);
            if (drOrg == null) throw new MaxLeafException(string.Format("goods_category not exist cat_id {0}",strKeyValue));

            string strK3FitemId = GetDestKeyValue(dbOrgWebReadCon, dbOrgWebWriteCon, dbDestK3Con, strKeyValue);
            if (strK3FitemId.Length > 0)
            {
                KeyValuePair<string, IDataParameter[]> kvpK3Fnumber = dbDestK3Con.CreateCondParam(new Dictionary<string, object>() { { "fitemid", strK3FitemId }, { "FItemClassID", strFItemClassID } });

                string strK3Fnumber = dbDestK3Con.GetValue("select Fnumber from t_item where FitemId=@fitemid and FItemClassID=@FItemClassID",kvpK3Fnumber.Value);
                if (strK3Fnumber.Split('.').Length != CvtFunc.ToInt(drOrg["cat_level"]))
                {
                    KeyValuePair<string, IDataParameter[]> kvpChlidK3Fnumber = dbDestK3Con.CreateCondParam(new Dictionary<string, object>() { { "Fnumber", string.Format("{0}.%",strK3Fnumber) }, { "FItemClassID", strFItemClassID } });
                    string strChlidK3Fnumber = dbDestK3Con.GetValue("select top 1 Fnumber from t_item where Fnumber like @Fnumber and FItemClassID=@FItemClassID", kvpChlidK3Fnumber.Value);
                    if (!string.IsNullOrEmpty(strChlidK3Fnumber))
                    {
                        throw new MaxLeafException(string.Format("Cannot delete fnumber {0} , it has children {1} ", strK3Fnumber, strChlidK3Fnumber));
                    }

                    this.Delete(dbOrgWebReadCon, dbOrgWebWriteCon, dbDestK3Con, strKeyValue);

                    new goods_mainGroupDAL(Const.FItemClassID_ItemGroup_1).Delete(dbDestK3Con, dbDestK3Con, dbDestK3Con, strK3FitemId);

                    new goods_mainGroupDAL(Const.FItemClassID_ItemGroup_2).Delete(dbDestK3Con, dbDestK3Con, dbDestK3Con, strK3FitemId);
                }
            }

            if (CvtFunc.ToInt(drOrg["cat_level"])<3)
            {
                return new goods_categoryGroupDAL().Update(dbOrgWebReadCon,dbOrgWebWriteCon, dbDestK3Con, strKeyValue);
            }
            int iDestKey= base.Update(dbOrgWebReadCon,dbOrgWebWriteCon, dbDestK3Con,   strKeyValue);


            new goods_mainGroupDAL(Const.FItemClassID_ItemGroup_1).Update(dbDestK3Con, dbDestK3Con, dbDestK3Con, iDestKey.ToString());

            new goods_mainGroupDAL(Const.FItemClassID_ItemGroup_2).Update(dbDestK3Con, dbDestK3Con, dbDestK3Con, iDestKey.ToString());

            return iDestKey;
        }


        protected override void DAL_GetFieldData(DBAccess dbOrgWebReadCon, DBAccess dbOrgWebWriteCon, DBAccess dbDestK3Con, string strK3FieldName, DataRow drOrgData, DataRow drDestData)
        {
            if (strK3FieldName.Equals("FitemID", StringComparison.InvariantCultureIgnoreCase))
            {

                if (CvtFunc.ToInt(drDestData[strK3FieldName]) != 0) return;
                if (CvtFunc.ToString(drDestData["FNumber"]).Length == 0)
                {
                     DAL_GetFieldData(dbOrgWebReadCon, dbOrgWebWriteCon,dbDestK3Con, "FNumber", drOrgData, drDestData);
                }
                string strFParentID = CvtFunc.ToString(new goods_categoryGroupDAL().GetDestMapKeyValue(dbOrgWebReadCon,dbOrgWebWriteCon, dbDestK3Con, CvtFunc.ToString(drOrgData["parent_id"])));
                //再FitemID
                drDestData[strK3FieldName] = GetFItemID(dbDestK3Con, strFParentID, CvtFunc.ToString(drDestData["FNumber"]), CvtFunc.ToString(drOrgData["cat_name"]));


            }
            else if (strK3FieldName.Equals("FNumber", StringComparison.InvariantCultureIgnoreCase))
            {


                drDestData[strK3FieldName] = GetFNumber(dbOrgWebReadCon, dbOrgWebWriteCon,dbDestK3Con, drOrgData, drDestData);
                
                
            }
            else if (strK3FieldName.Equals("FName", StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strK3FieldName] = drOrgData["cat_name"];
            }
            else if (strK3FieldName.Equals("FTaxRate", StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strK3FieldName] = 17;
            }
            else if (strK3FieldName.Equals("FOrderFlag", StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strK3FieldName] = 14270;
            }            
            else
            {
                drDestData[strK3FieldName] = 0;
            }            
        }
                

        private string GetFItemID( DBAccess dbDestK3Con, string strFParentID, string strFnumber, string strFName)
        {
            
            const int intFDetail = 1;
            
            string strFItemId = string.Empty;
            t_ItemDAL dal = new t_ItemDAL();



            strFItemId = dal.GetFItemId(dbDestK3Con, strFItemClassID, strFnumber.Split('.').Length, strFParentID, strFnumber, strFName, intFDetail);

            UpdateAccess(dbDestK3Con, strFItemId, strFParentID);

            return strFItemId;
        }

        private void UpdateAccess(DBAccess dbDestK3Con, string strFItemId, string strFParentID)
        {
            string strSql = @"
                if not exists(select * from access_t_ComCategory where FitemID=@FitemID)
                begin
                 Insert into access_t_ComCategory(FitemID,FParentIDX,FDataAccessView,FDataAccessEdit,FDataAccessDelete)
                 Values(@FitemID,@FParentIDX,convert(varbinary(7200),REPLICATE(char(255),100)),convert(varbinary(7200),REPLICATE(char(255),100)),convert(varbinary(7200),REPLICATE(char(255),100)))
                end
                ";
            dbDestK3Con.ExecuteSql(strSql, new SqlParameter[] { new SqlParameter("@FitemID", strFItemId), new SqlParameter("@FParentIDX", strFParentID) });
        }

        private string GetFNumber(DBAccess dbOrgWebReadCon, DBAccess dbOrgWebWriteCon, DBAccess dbDestK3Con, DataRow drOrgData, DataRow drDestData)
        {
            string strFParentID = CvtFunc.ToString(new goods_categoryGroupDAL().GetDestMapKeyValue(dbOrgWebReadCon,dbOrgWebWriteCon, dbDestK3Con, CvtFunc.ToString(drOrgData["parent_id"])));
            string strSql = "select FNumber from t_item where FitemID=@FitemID  and FItemClassID=@FItemClassID";
            string strParentNumber = dbDestK3Con.GetValue(strSql, new SqlParameter[] { new SqlParameter("@FitemID", strFParentID), new SqlParameter("@FItemClassID", strFItemClassID) });
            if (CvtFunc.ToLeftString(drDestData["FNumber"], strParentNumber.Length + 1).Equals(strParentNumber + "."))
            {
                return CvtFunc.ToString(drDestData["FNumber"]);
            }
            else
            {
                return string.Format("{0}.{1}", strParentNumber, GetMaxFNumber(dbDestK3Con, strParentNumber, Const.Len_Category));
            }
        }


        protected override void WriteK3Log(DBAccess dbDestK3Con, int intKeyValue)
        {
             string strSql = @"insert into mLog(logtype,keyvalue,logstatus)
                values(@logtype,@keyvalue,@logstatus)";
             dbDestK3Con.ExecuteSql(strSql, dbDestK3Con.CreateCondParam(new Dictionary<string, object>() { 
                 {"logtype",LogType.goods_category.ToString()}
                 ,{"keyvalue",intKeyValue.ToString()}
                 ,{"logstatus","1"}
             }).Value);
            
        }
        
    }
}